package com.dawn.monsterabc

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Base64
import com.example.crop_image_project.BitmapUtil
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import java.io.File
import java.io.FileOutputStream
import java.io.IOException


/**
 * dart 和 kotlin 交互
 */
class CustomServicePlugin(context: Context) : FlutterPlugin, MethodCallHandler {
    private var channel: MethodChannel? = null
    private var context: Context? = context
    val CHANNEL: String = "com.example.crop_image_project/asset_channel"


    override fun onAttachedToEngine(binding: FlutterPluginBinding) {
        context = binding.applicationContext
        channel = MethodChannel(binding.binaryMessenger, CHANNEL)
        channel!!.setMethodCallHandler(this)
    }


    override fun onDetachedFromEngine(binding: FlutterPluginBinding) {
        channel!!.setMethodCallHandler(null)
    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        when (call.method) {
            "processImages" -> {
                val imageString1 = call.argument<String>("image1")
                val imageString2 = call.argument<String>("image2")
                imageString1?.let {
                    handleImage(it, imageString2, result)
                } ?: result.error("IMAGE_ERROR", "Image data is null", null)
            }

            else -> result.notImplemented()
        }
    }
    private fun handleImage(
        encodedImage1: String,
        encodedImage2: String?,
        result: MethodChannel.Result
    ) {
        val decodedBytes1 = Base64.decode(encodedImage1, Base64.DEFAULT)
        val decodedBytes2 = Base64.decode(encodedImage2, Base64.DEFAULT)

        val maskBitMap = BitmapFactory.decodeByteArray(decodedBytes1, 0, decodedBytes1.size)
        val originBitMap = BitmapFactory.decodeByteArray(decodedBytes2, 0, decodedBytes2.size)

        var bitmapShow = BitmapUtil.cropContour(originBitMap, maskBitMap)
        val filePath = saveBitmap(bitmapShow)
        result.success(filePath)
    }

    /**
     * 保存bitmap到本地
     */
    private fun saveBitmap(bitmap: Bitmap): String {
        val file = File(context!!.getExternalFilesDir(null), "processed_image.png")
        try {
            FileOutputStream(file).use { output ->
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, output)
            }
        } catch (e: IOException) {
            throw RuntimeException(e)
        }
        return file.absolutePath
    }

}